package com.example.basketVoice

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import androidx.activity.ComponentActivity
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.core.app.ActivityCompat

import org.vosk.Recognizer

class SpeechService(
    private val recognizer: Recognizer,
    private val sampleRate: Int
) {
    private var audioRecord: AudioRecord? = null
    private var thread: Thread? = null
    private var isRunning = false


    fun startListening(context: Context) {
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            if (context is ComponentActivity) {
                val permissions = arrayOf(Manifest.permission.RECORD_AUDIO)
                ActivityCompat.requestPermissions(
                    context,
                    permissions,
                    101
                )
            }
            return
            return
        }

        // 原有录音启动代码
        audioRecord = AudioRecord(
            MediaRecorder.AudioSource.VOICE_RECOGNITION,
            sampleRate,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            AudioRecord.getMinBufferSize(
                sampleRate,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT
            ) * 10
        )

        isRunning = true
        audioRecord?.startRecording()

        thread = Thread {
            val buffer = ShortArray(1600)
            while (isRunning) {
                val len = audioRecord?.read(buffer, 0, buffer.size) ?: 0
                if (len > 0) {
                    recognizer.acceptWaveForm(buffer, len)
                }
            }
        }.apply { start() }
    }

    fun stopListening(): String {
        isRunning = false
        audioRecord?.stop()
        audioRecord?.release()
        thread?.join()
        return recognizer.result ?: "没有数据"
    }
}